<template>
  <div id="viewer" ref="panoshow"></div>
  <MarkerForm ref="formRef" @reloadList="initMarkers" @submit="getMarker" />
</template>

<script setup>
  import { ref, onMounted, onUnmounted, reactive, nextTick, createApp } from 'vue';
  import { Rate } from 'ant-design-vue';
  import 'ant-design-vue/dist/reset.css';
  import 'ant-design-vue';
  import { Viewer } from 'photo-sphere-viewer';
  import { useRoute } from 'vue-router';
  import { markerApi } from '/@/api/business/marker/marker-api';
  import MarkerForm from './components/marker-form.vue';
  import { MarkersPlugin } from 'photo-sphere-viewer/dist/plugins/markers';
  import { CompassPlugin } from 'photo-sphere-viewer/dist/plugins/compass';
  import markerRed from '../../../assets/images/picture/mark-red.png';
  import markerBlue from '../../../assets/images/picture/marker-blue.png';
  import { message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/system/user.js';
  import 'photo-sphere-viewer/dist/photo-sphere-viewer.css';
  import 'photo-sphere-viewer/dist/plugins/markers.css';
  import 'photo-sphere-viewer/dist/plugins/compass.css';
  const userStore = useUserStore();
  const route = useRoute();
  const panoshow = ref(null);
  let viewer = null;

  // 独立状态变量管理热点数据
  const currentHotspots = ref([]);

  // 初始化标记点数据
  const initMarker = ref([]);

  // 查询表单
  const queryFormState = {
    name: undefined, // 地点名称
    pageNum: 1,
    pageSize: 10,
  };
  const queryForm = reactive({ ...queryFormState });

  const formRef = ref();

  // 打开表单并传递点击位置的经纬度
  function showForm(data) {
    formRef.value.show(data);
  }

  // 封装 Viewer 初始化逻辑
  const initViewer = () => {
    if (!panoshow.value) return;
    const description =
      userStore.loginName === 'admin' ? '管理员您好，您可以通过点击全景图添加地点，点击标记点查看详情' : '游客您好，您可以点击标记点查看详情';

    const navbarConfig =
      userStore.loginName === 'admin'
        ? ['autorotate', 'zoom', 'caption', 'markers', 'markersList', 'description', 'download', 'fullscreen']
        : ['autorotate', 'zoom', 'caption', 'markers', 'markersList', 'description', 'fullscreen'];

    viewer = new Viewer({
      container: panoshow.value,
      panorama: pictureEntity.value.pictureUrl,
      caption: `拍摄时间: ${pictureEntity.value.pictureTime}, 图片名称: ${pictureEntity.value.pictureName}`,
      description: description,
      size: {
        width: '100%',
        height: '100%',
      },
      navbar: navbarConfig,
      autorotateDelay: 800,
      lang: {
        autorotate: '自动旋转',
        zoom: '缩放',
        zoomOut: '缩小',
        zoomIn: '放大',
        move: '移动',
        download: '下载',
        fullscreen: '全屏',
        menu: '菜单',
        twoFingers: '双指导航',
        ctrlZoom: 'ctrl + 滚轮缩放',
        loadError: '全景图加载失败',
        markers: '标记点',
        markersList: '标记点列表',
        description: '描述',
      },
      mousewheelCtrlKey: false,
      touchmoveTwoFingers: true,
      plugins: [
        [CompassPlugin, { hotspots: currentHotspots.value }],
        [MarkersPlugin, { markers: initMarker.value }],
      ],
    });
    const markersPlugin = viewer.getPlugin(MarkersPlugin);
    // 用户点击时创建新标记点
    viewer.on('click', (e, data) => {
      if (userStore.loginName !== 'admin') {
        return;
      }
      if (!data.rightclick) {
        showForm({ longitude: data.longitude, latitude: data.latitude });
      }
    });

    // 处理标记点交互
    markersPlugin.on('select-marker', (e, marker, data) => {
      console.log('marker', marker);

      const ratingValue = ref(marker.data.markerRating || 0);
      // 动态生成面板内容
      const panelContent = `
  <h1>详情</h1>
  <p><strong>地点名称:</strong> ${marker.data.markerName}</p>
  <p><strong>简介:</strong> ${marker.data.markerIntroduction || '暂无简介'}</p>
  <p><strong>类型:</strong> ${markerTypeMap[marker.data.markerType] || '未知类型'}</p> 
  <div style="display: flex !important; align-items: center;">
    <strong style="margin-right: 8px;">评分:</strong>
    <div id="dynamic-rate"></div>
  </div>
  <div>
    <div style="margin-top:15px"><strong>营业时间:</strong> ${marker.data.markerOpeningHours || '暂无'}</div>
    ${
      userStore.loginName === 'admin'
        ? `<button id="delete-marker-btn" style="position: absolute; bottom: 10px; right: 10px; padding: 5px 9px; font-size: 13px; background-color: #ff4d4f; color: white; border: none; border-radius: 4px; cursor: pointer;">删除标记</button>`
        : ''
    }
  </div>
`;

      // 显示面板内容
      viewer.panel.show({
        id: 'custom-panel',
        content: panelContent,
        width: '40%',
      });

      nextTick(() => {
        const rateContainer = document.getElementById('dynamic-rate');
        if (rateContainer) {
          createApp({
            components: { 'a-rate': Rate },
            data() {
              return { value: ratingValue.value };
            },
            template: `<a-rate v-model:value="value" />`,
          }).mount(rateContainer);
        }

        // 为删除按钮绑定点击事件
        const deleteButton = document.getElementById('delete-marker-btn');
        if (deleteButton) {
          deleteButton.addEventListener('click', async () => {
            try {
              const markerId = marker.id;
              await markerApi.delete(markerId);
              const markersPlugin = viewer.getPlugin(MarkersPlugin);
              markersPlugin.removeMarker(markerId);
              const compassPlugin = viewer.getPlugin(CompassPlugin);
              const updatedHotspots = currentHotspots.value.filter((hotspot) => hotspot.id !== markerId);
              if (compassPlugin && typeof compassPlugin.setHotspots === 'function') {
                compassPlugin.setHotspots(updatedHotspots);
                currentHotspots.value = updatedHotspots;
              }
              viewer.panel.hide();
            } catch (error) {
              console.error('删除标记点失败:', error);
            }
          });
        }
      });
    });
  };
  const markerTypeMap = {
    GOURMET_DINING: '美食餐饮',
    TOURIST_ATTRACTION: '旅游景点',
    RECREATION: '休闲娱乐',
    LIFE_SERVICES: '生活服务',
    OTHER: '其他',
  };
  // 添加标记点
  async function getMarker(formData) {
    if (userStore.loginName !== 'admin') {
      return;
    }
    const markersPlugin = viewer.getPlugin(MarkersPlugin);
    const compassPlugin = viewer.getPlugin(CompassPlugin);
    // 动态更新热点数据
    const updateCompassHotspots = (newHotspots) => {
      if (compassPlugin && typeof compassPlugin.setHotspots === 'function') {
        compassPlugin.setHotspots(newHotspots);
        currentHotspots.value = newHotspots;
      } else {
        console.error('CompassPlugin 不支持 setHotspots 方法');
      }
    };
    console.log(formData);

    // 创建新的标记点
    const newMarker = {
      id: `marker-${Date.now()}`,
      longitude: formData.longitude,
      latitude: formData.latitude,
      image: markerRed,
      width: 32,
      height: 32,
      anchor: 'bottom center',
      tooltip: formData.markerName || '默认提示信息',
      data: {
        markerId: formData.markerId,
        addressId: formData.addressId,
        markerName: formData.markerName,
        markerLongitude: formData.markerLongitude,
        markerLatitude: formData.markerLatitude,
        markerIntroduction: formData.markerIntroduction || '默认提示信息',
        markerType: formData.markerType || '默认提示信息',
        markerRating: formData.markerRating || '默认提示信息',
        markerOpeningHours: formData.markerOpeningHours || '默认提示信息',
      },
    };

    formData.markerId = newMarker.id;
    formData.addressId = route.query.addressId;

    try {
      await markerApi.add(formData);
      markersPlugin.addMarker(newMarker);
      // 同步更新 CompassPlugin 的热点数据
      const radiansToDegrees = (radians) => ((radians * 180) / Math.PI).toFixed(0);
      const newHotspot = { id: newMarker.id, longitude: `${radiansToDegrees(formData.longitude)}deg`, color: 'red' };
      const uniqueHotspots = [...new Map([...currentHotspots.value, newHotspot].map((h) => [h.longitude, h])).values()];
      updateCompassHotspots(uniqueHotspots);
    } catch (error) {
      console.error('获取图标地点详情失败:', error);
    }
  }
  const generateHotspotsFromMarkers = (markers) => {
    return markers.map((marker) => ({
      id: marker.data.markerId,
      longitude: `${((marker.longitude * 180) / Math.PI).toFixed(0)}deg`,
      color: 'blue',
    }));
  };
  // 获取标记点列表
  async function initMarkers() {
    const res = await markerApi.getMarkerListByAddressId(route.query.addressId);
    initMarker.value = res.data.map((item) => ({
      id: item.markerId,
      longitude: parseFloat(item.markerLongitude),
      latitude: parseFloat(item.markerLatitude),
      image: markerBlue,
      width: 32,
      height: 32,
      anchor: 'bottom center',
      tooltip: item.markerName,
      data: {
        markerId: item.markerId,
        addressId: item.addressId,
        markerName: item.markerName,
        markerLongitude: item.markerLongitude,
        markerLatitude: item.markerLatitude,
        markerIntroduction: item.markerIntroduction || '暂无',
        markerType: item.markerType,
        markerRating: item.markerRating || '暂无',
        markerOpeningHours: item.markerOpeningHours || '暂无',
      },
    }));
    currentHotspots.value = generateHotspotsFromMarkers(initMarker.value);
  }

  onMounted(async () => {
    pictureEntity.value.pictureUrl = route.query.pictureUrl;
    pictureEntity.value.pictureTime = route.query.pictureTime;
    pictureEntity.value.pictureName = route.query.pictureName;
    await initMarkers();
    nextTick(() => {
      initViewer();
    });
    // 根据用户权限显示提示信息
    if (userStore.loginName === 'admin') {
      message.info('管理员您好，您可以通过点击全景图添加地点，点击标记点查看详情');
    } else {
      message.info('可以点击标记点查看详情');
    }
  });

  onUnmounted(() => {
    if (viewer) {
      viewer.destroy();
    }
  });

  const pictureEntity = ref({
    pictureUrl: undefined,
    pictureTime: undefined,
    pictureName: undefined,
  });
</script>

<style scoped>
  #viewer {
    width: 100%;
    height: 100vh;
  }
</style>
